package com.huanletao.httpclient;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.ClientProtocolException;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.DefaultConnectionKeepAliveStrategy;
import org.apache.hc.client5.http.impl.classic.AbstractHttpClientResponseHandler;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.*;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.net.URIBuilder;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.apache.hc.core5.util.TimeValue;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * </p>
 *
 * @package: ${PAGENAME}
 * @Description:
 * @className: HttpClientUtil
 * @author: @NNCSKJ ADMIN
 * @copyright: Copyright (c) 2022/6/11 9:55
 * @version: V1.0
 */
public class HttpClientUtil {

    /**
     * 使用全局单例请求客户端
     */
    private static CloseableHttpClient httpClient;
    private static final ObjectMapper jackson = new ObjectMapper();

    static {
        //设置连接池
        PoolingHttpClientConnectionManager connManager = PoolingHttpClientConnectionManagerBuilder
                .create()
                .setMaxConnPerRoute(5)
                .setMaxConnTotal(100)
                .setSSLSocketFactory(getSslConnectionSocketFactory())
                .build();
        //设置请求参数
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionKeepAlive(TimeValue.ofSeconds(10))
                .setConnectTimeout(6000, TimeUnit.MICROSECONDS)
                .setConnectionRequestTimeout(6000,TimeUnit.MICROSECONDS)
                .build();



        httpClient = HttpClients.custom()
                .setConnectionManager(connManager)
                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
                .setDefaultRequestConfig(requestConfig)
                .build();


    }

    /**
     * 支持SSL
     *
     * @return SSLConnectionSocketFactory
     */
    private static SSLConnectionSocketFactory getSslConnectionSocketFactory() {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, s) -> true;
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
    }


    /**
     * 带参数的get请求
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public static HttpResult doGet(String url, Map<String, Object> map) throws Exception {
        // 声明URIBuilder
        ClassicHttpRequest request  = ClassicRequestBuilder.get(url).build();
        if (map != null) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                request = ClassicRequestBuilder.get(url)
                        .addParameter(entry.getKey(),entry.getValue().toString())
                        .build();
            }

        }
        return httpClient.execute(request,new CustomResponseHandler());
    }

    /**
     * 不带参数的get请求
     */
    public static HttpResult doGet(String url) throws Exception {
        return doGet(url, null);
    }

    /**
     * 带参数的post请求
     */
    public static HttpResult doPostJson(String url, Map<String, Object> reqMap, Map<String, String> headersMap)
            throws Exception {

        ClassicHttpRequest request = new BasicClassicHttpRequest(Method.POST, url);
        request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON);
        for (Map.Entry<String, String> entry : headersMap.entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }

        if (reqMap != null) {
            StringEntity formEntity = new StringEntity(jackson.writeValueAsString(reqMap),StandardCharsets.UTF_8);
            request.setEntity(formEntity);
        }
        return httpClient.execute(request,new CustomResponseHandler());
    }

    /**
     * 不带参数的post请求
     */
    public static HttpResult doPostJson(String url) throws Exception {
        return doPostJson(url, null, null);
    }

    /**
     * 发送form 表单形式的post请求。
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     * @throws ParseException
     */
    public static HttpResult doPostForm(String url, Map<String, String> params) throws IOException, ParseException {

        BasicClassicHttpRequest request = new BasicClassicHttpRequest(Method.POST, url);
        request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED);
        List<NameValuePair> parameters = new ArrayList<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            BasicNameValuePair valuePair = new BasicNameValuePair(entry.getKey(), entry.getValue());
            parameters.add(valuePair);
        }
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
        request.setEntity(formEntity);

        return httpClient.execute(request,new CustomResponseHandler());
    }


    /**
     * 带参数的Put请求
     */
    public static HttpResult doPut(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
        ClassicHttpRequest request = new BasicClassicHttpRequest(Method.PUT, url);
        // 判断map不为空
        if (map != null) {
            // 声明存放参数的List集合
            List<NameValuePair> params = new ArrayList<>();

            // 遍历map，设置参数到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
            request.setEntity(formEntity);
        }
        return httpClient.execute(request,new CustomResponseHandler());
    }

    /**
     * 带参数的Delete请求
     */
    public static HttpResult doDelete(String url, Map<String, Object> map) throws Exception {
        // 声明URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        // 判断参数map是否为非空
        if (map != null) {
            // 遍历参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 设置参数
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());

            }
        }

        ClassicHttpRequest request = new BasicClassicHttpRequest(Method.DELETE, url);
        return httpClient.execute(request,new CustomResponseHandler());
    }


    /**
     * 静态内部类。
     */
    public static class HttpResult {
        private int code;
        private String body;

        public HttpResult() {
        }

        public static HttpResult build(int code, String body){
            return new HttpResult(code, body);
        }

        public HttpResult(int code, String body) {
            this.code = code;
            this.body = body;
        }

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public String getBody() {
            return body;
        }

        public void setBody(String body) {
            this.body = body;
        }
    }

    /**
     * 自定义响应结果处理
     *
     */
    public static class CustomResponseHandler extends AbstractHttpClientResponseHandler<HttpResult> {

        @Override
        public HttpResult handleEntity(HttpEntity entity) throws IOException {
            try {
                return HttpResult.build(200,EntityUtils.toString(entity));
            } catch (ParseException var3) {
                throw new ClientProtocolException(var3);
            }
        }

        @Override
        public HttpResult handleResponse(ClassicHttpResponse response) throws IOException {
            return super.handleResponse(response);
        }
    }
}
